package com.good.app.net

import io.reactivex.Observable
import io.reactivex.ObservableSource
import io.reactivex.ObservableTransformer
import io.reactivex.functions.Function

object ResponseTransfer {

    fun <T> handleResult(): ObservableTransformer<Response<T>, T> {
        return ObservableTransformer<Response<T>, T>{ upstream ->
            upstream.onErrorResumeNext(ErrorResumeFunction<T>())
                .flatMap(ResponseFunction<T>())
        }
    }

    private class ErrorResumeFunction<T> : Function<Throwable, ObservableSource<out Response<T>>> {

        override fun apply(throwable: Throwable): ObservableSource<out Response<T>> {
            return Observable.error(CustomException.handleException(throwable))
        }
    }

    private class ResponseFunction<T> : Function<Response<T>, ObservableSource<T>> {

        @Throws(Exception::class)
        override fun apply(tResponse: Response<T>): ObservableSource<T> {
            val code = tResponse.code
            val msg = tResponse.msg
            when (code) {
                "000" -> return Observable.just(tResponse.data)
                "602" -> return Observable.error(ApiException(code.toString(), msg.toString()))
                else -> return Observable.error(ApiException(code.toString(), msg.toString()))
            }
        }
    }
}